{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "import math\n",
    "FLAGS = None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "导入数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-cf0ad10d35ed>:3: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From /home/sika/miniconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From /home/sika/miniconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting MNIST_data/train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From /home/sika/miniconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting MNIST_data/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /home/sika/miniconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting MNIST_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /home/sika/miniconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = 'MNIST_data/'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_layer(inputs,in_size,out_size,activation_function=None):\n",
    "    #构建权重\n",
    "    stddev1=2/math.sqrt(in_size+out_size)\n",
    "    weights=tf.Variable(tf.truncated_normal([in_size,out_size],mean=0.0,stddev=stddev1,seed=2))\n",
    "    #构建偏置\n",
    "    biases=tf.Variable(tf.zeros([out_size])+0.01)\n",
    "    #矩阵相乘\n",
    "    logits=tf.matmul(inputs,weights)+biases\n",
    "    if activation_function is None:\n",
    "        outputs=logits\n",
    "    else:\n",
    "        outputs=activation_function(logits)\n",
    "    return outputs #得到输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "learning_rate=0.5\n",
    "batch_size=100\n",
    "total_steps=3000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# placeholder\n",
    "# 输入图片为28 x 28 像素 = 784\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "# 输出为0-9的one-hot编码\n",
    "y = tf.placeholder(tf.float32, [None, 10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "ground_truth=tf.placeholder(tf.float32,[None,10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "h1=add_layer(x,784,500,activation_function=tf.nn.relu)\n",
    "h2=add_layer(h1,500,300,activation_function=tf.nn.relu)\n",
    "y=add_layer(h2,300,10,activation_function=None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-8-934467f3ce38>:1: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See `tf.nn.softmax_cross_entropy_with_logits_v2`.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=ground_truth,logits=y))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_step=tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "init_op=tf.global_variables_initializer()\n",
    "sess=tf.Session()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "current epoch:0.0 accuracy:0.2496\n",
      "current epoch:1.0 accuracy:0.8676\n",
      "current epoch:2.0 accuracy:0.9487\n",
      "current epoch:3.0 accuracy:0.958\n",
      "current epoch:4.0 accuracy:0.9585\n",
      "current epoch:5.0 accuracy:0.9639\n",
      "current epoch:6.0 accuracy:0.9681\n",
      "current epoch:7.0 accuracy:0.9699\n",
      "current epoch:8.0 accuracy:0.9727\n",
      "current epoch:9.0 accuracy:0.9735\n",
      "current epoch:10.0 accuracy:0.9712\n",
      "current epoch:11.0 accuracy:0.9717\n",
      "current epoch:12.0 accuracy:0.975\n",
      "current epoch:13.0 accuracy:0.9738\n",
      "current epoch:14.0 accuracy:0.9714\n",
      "current epoch:15.0 accuracy:0.9777\n",
      "current epoch:16.0 accuracy:0.9772\n",
      "current epoch:17.0 accuracy:0.9786\n",
      "current epoch:18.0 accuracy:0.9758\n",
      "current epoch:19.0 accuracy:0.9783\n",
      "current epoch:20.0 accuracy:0.9792\n",
      "current epoch:21.0 accuracy:0.977\n",
      "current epoch:22.0 accuracy:0.9784\n",
      "current epoch:23.0 accuracy:0.9771\n",
      "current epoch:24.0 accuracy:0.9815\n",
      "current epoch:25.0 accuracy:0.9791\n",
      "current epoch:26.0 accuracy:0.9816\n",
      "current epoch:27.0 accuracy:0.9788\n",
      "current epoch:28.0 accuracy:0.9807\n",
      "current epoch:29.0 accuracy:0.9784\n"
     ]
    }
   ],
   "source": [
    "for epoch in range(total_steps):\n",
    "    bath_xs,batch_ys=mnist.train.next_batch(batch_size)\n",
    "    sess.run(train_step,feed_dict={x:bath_xs,ground_truth:batch_ys})\n",
    "    if epoch % 100==0:\n",
    "        correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(ground_truth,1))\n",
    "        acurracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n",
    "        print(\"current epoch:%s accuracy:%s\"%(epoch/100,sess.run(acurracy,feed_dict={x: mnist.test.images, ground_truth: mnist.test.labels})))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以看到准确率在0.98左右了，两个隐层只训练了大概3000次准确率就大大提高了。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
